import { useEffect } from "react";
import { View } from "react-native";

import useLoading from "@/hooks/useLoading";
import useModalBox from "@/hooks/useModalBox";
import useDialog from "@/hooks/useDialog";

import MToast, { showMessage, hideMessage } from "@/components/Message";
import globalMethods from "./index";
import config from "@/config";

type Props = {
  children: React.ReactNode;
};

/** 添加全局方法 */
const GlobalMethodsProvider = (props: Props) => {
  console.log("GlobalMethodsProvider render");
  const { Loading, showLoading, hideLoading } = useLoading();
  const { ModalBox, show: showModalBox, hide: hideModalBox } = useModalBox();
  const { Dialog, show: showDialog, hide: hideDialog } = useDialog();

  useEffect(() => {
    globalMethods.$showLoading = showLoading;
    globalMethods.$hideLoading = hideLoading;
    globalMethods.$showMessage = showMessage;
    globalMethods.$success = (message: string, duration = (config.messageVisibilityTime * 1.5)) => {
      showMessage({ type: "success", message, visibilityTime: duration });
    };
    globalMethods.$error = (message: string, duration = (config.messageVisibilityTime * 1.5)) => {
      showMessage({ type: "error", message, visibilityTime: duration });
    };
    globalMethods.$warning = (message: string, duration = (config.messageVisibilityTime * 1.5)) => {
      showMessage({ type: "warning", message, visibilityTime: duration });
    };
    globalMethods.$hideMessage = hideMessage;
    globalMethods.$showModalBox = showModalBox;
    globalMethods.$hideModalBox = hideModalBox;
    globalMethods.$showDialog = showDialog;
    globalMethods.$hideDialog = hideDialog;

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <View style={{ flex: 1 }}>
      {props.children}

      {/* 全局 Loading */}
      {Loading}

      {/* 全局 ModalBox */}
      {ModalBox}

      {/* 全局 Dialog */}
      {Dialog}

      {/* 全局 Toast, 放到最后(这里还是会被 Model 遮挡) */}
      {MToast}
    </View>
  );
};

export default GlobalMethodsProvider;
